package com.me.study.javaCore.annotation;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * 工具类：通过实体生产查询 sql
 *
 * @author ME
 * @date   2019/10/13
 */
public class CommonUtil {

    public static String buildQuerySqlForEntity(Object object) {
        Class<?> clazz = object.getClass();
        if (clazz.isAnnotationPresent(MyEntity.class)) {
            try {
                StringBuilder sql = new StringBuilder("INSERT INTO ");
                StringBuilder columns = new StringBuilder();
                StringBuilder values = new StringBuilder();
                for (Field field : clazz.getDeclaredFields()) {
                    field.setAccessible(true);
                    columns.append(field.getName()).append(",");
                    values.append('\'').append(field.get(object)).append("\',");
                }
                MyEntity myEntity = clazz.getAnnotation(MyEntity.class);
                sql.append(StringUtils.isNotBlank(myEntity.value()) ? myEntity.value() : myEntity.name())
                        .append('(').append(columns.substring(0, columns.length() - 1)).append(") VALUES (")
                        .append(values.substring(0, values.length() - 1)).append(')');
                return sql.toString();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
